import {
  asyncTraumaRoutes,
  asyncRoutes,
  constantRoutes,
  notFoundRoutes
} from '@/router'
import store from '@/store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) { // roles是后台返回的权限 ['admin', 'editor']
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role)) // 判断后台返回的权限是否在预先设定的权限里面
  } else {
    return true
  }
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
/* 筛选不需要权限以及需要权限，并且后台返回数据符合该权限的所有路由对象 */
export function filterAsyncRoutes(routes, roles) { // routes为asyncRoutes数组(前台定义路由) roles为后台返回数据
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    } // asyncRoutes中每个路由信息对象
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/* *********改造中 ********/
// function hasPermissionNew(menus, route) { // roles是后台返回的权限 ['admin', 'editor']
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role)) // 判断后台返回的权限是否在预先设定的权限里面
//   } else {
//     return true
//   }
// }
/* 筛选不需要权限以及需要权限，并且后台返回数据符合该权限的所有路由对象 */
export function filterAsyncRoutesNew(routes, menus) { // routes为asyncRoutes数组 , menus为后台返回用户角色权限菜单
  const nameList = menus.map(el => el.name)
  // const res = routes.filter(route => !route.meta || nameList.includes(route.meta.title))
  const res = routes.filter(route => route.meta && nameList.includes(route.meta.title))
  console.log('resRoyter', res)
  return res
}
/** ********改造中 -End *********/

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes, notFoundRoutes)
  }
}

const actions = {
  generateRoutes({ commit }, userInfo) {
    return new Promise(resolve => {
      let accessedRoutes
      console.log(store.getters.webcfg.split('|')[1], 'getters')
      let trauma = store.getters.webcfg.split('|')[1]

      if (trauma && trauma == 'trauma') {
        accessedRoutes = filterAsyncRoutesNew(asyncTraumaRoutes, userInfo.menuList) // 根据后台返回的权限（roles）进行筛选
      } else {
        accessedRoutes = filterAsyncRoutesNew(asyncRoutes, userInfo.menuList) // 根据后台返回的权限（roles）进行筛选
      }
      // if (trauma && trauma == 'trauma') {
      //   accessedRoutes = asyncTraumaRoutes || []
      // } else {
      //   accessedRoutes = asyncRoutes || []
      // }

      // if (userInfo.administrators) { // 如果是管理员则使用预先定义的路由信息，不需要筛选
      //   if (trauma && trauma == 'trauma') {
      //     accessedRoutes = asyncTraumaRoutes || []
      //   } else {
      //     accessedRoutes = asyncRoutes || []
      //   }
      // } else {
      //   if (trauma && trauma == 'trauma') {
      //     accessedRoutes = filterAsyncRoutesNew(asyncTraumaRoutes, userInfo.menuList) // 根据后台返回的权限（roles）进行筛选
      //   } else {
      //     accessedRoutes = filterAsyncRoutesNew(asyncRoutes, userInfo.menuList) // 根据后台返回的权限（roles）进行筛选
      //   }
      // }


      commit('SET_ROUTES', accessedRoutes)
      // store.commit('user/SET_ROUTERPOWERS', true)
      store.commit('user/SET_HOMEPATH', accessedRoutes.length > 0 ? accessedRoutes[0].redirect || accessedRoutes[0].path : '')
      store.commit('user/SET_ROUTERPOWERS', accessedRoutes)

      resolve(accessedRoutes)
    })
  }
  // generateRoutes({ commit }, roles) {
  //   roles = Array.isArray(roles) ? roles : JSON.parse(roles)
  //   return new Promise(resolve => {
  //     let accessedRoutes
  //     if (roles.includes('SUPER_ADMIN') || roles.includes('LITTLE_ADMIN')) { // 如果是管理员则使用预先定义的路由信息，不需要筛选
  //       accessedRoutes = asyncRoutes || []
  //     } else {
  //       accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) // 根据后台返回的权限（roles）进行筛选
  //     }
  //     commit('SET_ROUTES', accessedRoutes)
  //     store.commit('user/SET_ROUTERPREPARE', true)
  //     resolve(accessedRoutes)
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
